/**
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.dao.db.exec;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cc.aileron.accessor.PojoAccessorValueNotFoundException;
import cc.aileron.accessor.PojoPropertiesNotFoundException;
import cc.aileron.commons.util.CastUtils;
import cc.aileron.dao.db.G2DaoSerial;
import cc.aileron.dao.identifier.pojo.G2DaoIdentifier;

import com.google.inject.Singleton;

/**
 * @author Aileron
 * 
 */
@Singleton
public class G2DaoSerialNoneGeneratedKeys implements G2DaoSerial
{
    /*
     * (非 Javadoc)
     * 
     * @see
     * cc.aileron.dao.db.method.serial.DbExecuteSerial#getSerialNumber(java.
     * sql.PreparedStatement, java.lang.String, java.lang.Object)
     */
    public void getSerialNumber(final PreparedStatement statement,
            final String name, final Object object)
            throws SQLException, PojoAccessorValueNotFoundException,
            PojoPropertiesNotFoundException
    {
        setId(statement.getResultSet(), name, object);
        while (statement.getMoreResults())
        {
            setId(statement.getResultSet(), name, object);
        }
    }

    /**
     * @param rs
     * @param name
     * @param object
     * @throws SQLException
     * @throws PojoPropertiesNotFoundException
     * @throws PojoAccessorValueNotFoundException
     */
    private void setId(final ResultSet rs, final String name,
            final Object object)
            throws SQLException, PojoAccessorValueNotFoundException,
            PojoPropertiesNotFoundException
    {
        if (!(G2DaoIdentifier.class.isInstance(object)))
        {
            return;
        }
        if (rs == null)
        {
            return;
        }
        if (rs.next())
        {
            final int value = rs.getInt(1);
            CastUtils.<G2DaoIdentifier<Integer>> cast(object).id(value);
        }
        rs.close();
    }
}